import prisma from '@/server/lib/prisma';
import { Prisma } from '@prisma/client';

export default defineEventHandler(async (event) => {
  try {
    const query = getQuery(event);
    const page = Number(query.page || 1);
    const pageSize = Number(query.pageSize || 10);

    const where: Prisma.sys_roleWhereInput = {};
    if (query.roleName) {
      where.roleName = {
        contains: query.roleName as string,
      }
    }
    if (query.roleKey) {
      where.roleKey = {
        contains: query.roleKey as string,
      }
    }
    if (query.status) {
      where.status = query.status as string;
    }
    if (query.startTime && query.endTime) {
      where.createTime = {
        gte: new Date(query.startTime + ' 00:00:00').toISOString(),
        lte: new Date(query.endTime + ' 23:59:59').toISOString(),
      }
    }

    const result = await prisma.sys_role.findMany({
      where,
      orderBy: {
        roleSort: 'asc',
      },
      skip: (page - 1) * pageSize,
      take: pageSize,
      include: {
        menus: true,
      }
    })
    
    return {
      code: 200,
      data: result,
    }
  } catch (e) {
    throw e;
  } finally {
    await prisma.$disconnect(); // 关闭连接
  }
})